<template>
  <div class="data-tables">
    <div class="page-header">
      <h2>数据中心</h2>
      <el-tabs v-model="activeTab" class="data-tabs">
        <el-tab-pane label="实时数据" name="realtime">
          <div class="tables-grid">
            <el-card
              v-for="table in tables"
              :key="table.id"
              class="table-card"
              @click.stop="viewTable(table)"
            >
              <template #header>
                <div class="card-header">
                  <span class="table-name">{{ table.name }}</span>
                  <el-tag size="small" type="success">实时</el-tag>
                </div>
              </template>
              <div class="card-content">
                <div class="info-item">
                  <span class="label">更新时间：</span>
                  <span class="value">{{ formatTime(table.updateTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">数据量：</span>
                  <span class="value">{{ table.count || 0 }} 条</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        <el-tab-pane label="备份数据" name="backup">
          <div class="coming-soon">
            备份数据功能开发中...
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      v-model="tableDialogVisible"
      :title="currentTable?.name"
      width="90%"
      class="table-dialog"
      destroy-on-close
      @open="handleDialogOpen"
      @closed="handleDialogClose"
    >
      <div class="table-toolbar">
        <el-space>
          <el-button type="primary" @click="refreshTableData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-space>

        <el-space>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索..."
            clearable
            @clear="handleSearch"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-space>
      </div>

      <el-table
        :data="filteredTableData"
        style="width: 100%"
        height="calc(80vh - 200px)"
        v-loading="loading"
        border
      >
        <el-table-column
          v-for="column in tableColumns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          sortable
        />
      </el-table>

      <div class="table-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Download, Refresh } from '@element-plus/icons-vue';

// 基础状态
const activeTab = ref('realtime');
const tableDialogVisible = ref(false);
const loading = ref(false);
const currentTable = ref(null);
const searchKeyword = ref('');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(20);
const totalCount = ref(0);

// 表格数据
const tables = ref([
  {
    id: 'AA',
    name: 'AA表',
    updateTime: new Date().toISOString(),
    count: 0,
    description: '实时数据表'
  }
]);

// 表格数据
const tableData = ref([]);
const tableColumns = ref([
  { prop: 'id', label: 'ID', width: 80, sortable: true },
  { prop: 'created_at', label: '创建时间', width: 180, sortable: true,
    formatter: (row, column, cellValue) => {
      return new Date(cellValue).toLocaleString();
    }
  },
  { prop: 'timestamp', label: '时间戳', width: 180, sortable: true,
    formatter: (row, column, cellValue) => {
      return cellValue && cellValue !== '0001-01-01T00:00:00Z' 
        ? new Date(cellValue).toLocaleString() 
        : '-';
    }
  },
  { prop: 'data', label: '数据', minWidth: 200,
    formatter: (row, column, cellValue) => {
      if (!cellValue) return '-';
      try {
        return typeof cellValue === 'string' ? cellValue : JSON.stringify(cellValue);
      } catch (e) {
        return '-';
      }
    }
  }
]);

// 过滤后的表格数据
const filteredTableData = computed(() => {
  if (!searchKeyword.value) {
    return tableData.value;
  }

  return tableData.value.filter(row => {
    return Object.values(row).some(value => 
      String(value).toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  });
});

// 初始化
onMounted(() => {
  // 初始加载表格列表
  loadTableList();
});

// 加载表格列表
const loadTableList = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('https://penglink.pcwxcn.top/api/data/tables', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error('获取表格列表失败');
    }

    const result = await response.json();
    if (result.code === 200) {
      // 暂时只显示AA表
      tables.value = [{
        id: 'AA',
        name: 'AA表',
        updateTime: new Date().toISOString(),
        count: 0,
        description: '实时数据表'
      }];
    }
  } catch (error) {
    console.error('Load tables error:', error);
    ElMessage.error(error.message);
  }
};

// 查看表格数据
const viewTable = async (table) => {
  currentTable.value = table;
  tableDialogVisible.value = true;
};

// 处理对话框打开
const handleDialogOpen = () => {
  loadTableData();
};

// 处理对话框关闭
const handleDialogClose = () => {
  tableData.value = [];
  totalCount.value = 0;
  currentPage.value = 1;
  searchKeyword.value = '';
};

// 加载表格数据
const loadTableData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await fetch('https://penglink.pcwxcn.top/api/data', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        table_name: 'AA',
        page: currentPage.value,
        page_size: pageSize.value
      })
    });

    if (!response.ok) {
      throw new Error('获取数据失败');
    }

    const result = await response.json();
    if (result.code === 200 && Array.isArray(result.data)) {
      tableData.value = result.data;
      totalCount.value = result.data.length;
      
      // 更新表格信息
      if (currentTable.value) {
        currentTable.value.updateTime = new Date().toISOString();
        currentTable.value.count = result.data.length;
      }

      // 更新表格列表中的计数
      const index = tables.value.findIndex(t => t.id === 'AA');
      if (index !== -1) {
        tables.value[index].count = result.data.length;
        tables.value[index].updateTime = new Date().toISOString();
      }
    } else {
      throw new Error(result.message || '数据格式错误');
    }
  } catch (error) {
    console.error('Load data error:', error);
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};

// 刷新表格数据
const refreshTableData = () => {
  if (currentTable.value) {
    loadTableData();
  }
};

// 导出数据
const exportData = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  // 创建CSV内容
  const headers = tableColumns.value.map(col => col.label).join(',');
  const rows = tableData.value.map(row => {
    return tableColumns.value.map(col => {
      const cellValue = row[col.prop];
      return col.formatter ? col.formatter(row, col, cellValue) : cellValue;
    }).join(',');
  });

  const csvContent = [headers, ...rows].join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  
  link.setAttribute('href', url);
  link.setAttribute('download', `${currentTable.value?.name || 'data'}_${new Date().toISOString().split('T')[0]}.csv`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 自动刷新
let refreshInterval = null;

const startAutoRefresh = () => {
  if (refreshInterval) return;
  refreshInterval = setInterval(() => {
    if (tableDialogVisible.value && currentTable.value) {
      loadTableData();
    }
  }, 5000); // 每5秒刷新一次
};

// 监听对话框状态
watch(tableDialogVisible, (newVal) => {
  if (newVal) {
    startAutoRefresh();
  } else {
    stopAutoRefresh();
  }
});

// 组件卸载时清理
onUnmounted(() => {
  stopAutoRefresh();
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleString();
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
};
</script>

<style scoped>
.data-tables {
  height: 100%;
  background-color: #f5f7fa;
}

.page-header {
  padding: 20px;
}

.page-header h2 {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #303133;
}

.tables-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.table-card {
  cursor: pointer;
  transition: all 0.3s;
}

.table-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-name {
  font-size: 16px;
  font-weight: bold;
}

.card-content {
  padding: 10px 0;
}

.info-item {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.info-item .label {
  color: #909399;
}

.table-toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.coming-soon {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>
